package com.itwmk.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itwmk.config.RedisConfig;
import com.itwmk.entity.User;
import com.itwmk.service.impl.UserService;
import com.itwmk.utils.BaseContext;
import com.itwmk.utils.R;
import com.itwmk.utils.SMSUtils;
import com.itwmk.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wmk
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @PostMapping("sendMsg")
    public R<String> sentMsg(@RequestBody User user, HttpServletRequest request){
        String phone = user.getPhone();
        if (StringUtils.hasLength(phone)){
            String code= String.valueOf(ValidateCodeUtils.generateValidateCode(4));
            SMSUtils.sendMessage("短信签名","",phone,code);
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
//            request.getSession().setAttribute(phone,code);
            log.info("code：{}",code);
            return R.success("发送成功");
        }
        return R.error("发送失败");

    }

    @PostMapping("login")
    public R<User> login(@RequestBody Map map,HttpServletRequest request){

        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
//        Object c = request.getSession().getAttribute(phone);
        Object c = redisTemplate.opsForValue().get(phone);
        log.info(code);
        if (c!=null&&c.equals(code)){
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

            wrapper.eq(User::getPhone,phone);
            User user = userService.getOne(wrapper);
            if (user==null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            request.getSession().setAttribute("user",user.getId());

            redisTemplate.delete(phone);
            return R.success(user);
        }

        return R.error("登录失败");
    }
}
